//
//  xmppmannger.m
//  xmppones
//
//  Created by 李立达 on 2017/2/21.
//  Copyright © 2017年 李立达. All rights reserved.
//

#import "xmppmannger.h"


@interface xmppmannger ()<XMPPStreamDelegate,XMPPRosterDelegate,XMPPRosterMemoryStorageDelegate,UIAlertViewDelegate>
@end

#define LLDHOST @"192.168.0.103"
#define DOMAINT @"lilida"
@implementation xmppmannger


+(instancetype)shareInitOnes
{
    static xmppmannger *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[xmppmannger alloc]init];
    });
    return manager;
}
xmppmannger* getXMPPManager()
{
    xmppmannger  *manager = [xmppmannger shareInitOnes];
    return manager;
}
-(instancetype)init
{
    if(self == [super init])
    {
        [self initalldata];
    }
    return self;
}


-(void)initalldata
{
    if(self.xmppstream == nil)
    {
        self.xmppstream = [[XMPPStream alloc]init];
        [self.xmppstream setHostName:LLDHOST];
        [self.xmppstream setHostPort:5222];
        [_xmppstream setKeepAliveInterval:30];
        [_xmppstream setEnableBackgroundingOnSocket:YES];
        [self.xmppstream addDelegate:self delegateQueue:dispatch_get_main_queue()];
        //重新连接模块
        _xmppReconnect = [[XMPPReconnect alloc] initWithDispatchQueue:dispatch_get_main_queue()];
        [_xmppReconnect setAutoReconnect:YES];
        [_xmppReconnect activate:_xmppstream];
        //流管理模块
        _streamStorage = [[XMPPStreamManagementMemoryStorage alloc] init];
        _xmppStreamManagement = [[XMPPStreamManagement alloc] initWithStorage:_streamStorage];
        [_xmppStreamManagement setAutoResume:YES];
        [_xmppStreamManagement addDelegate:self delegateQueue:dispatch_get_main_queue()];
        [_xmppStreamManagement activate:_xmppstream];
        //好友模块
        _xmpprostermemorystorage = [[XMPPRosterMemoryStorage alloc]init];
        _xmpproster = [[XMPPRoster alloc]initWithRosterStorage:_xmpprostermemorystorage dispatchQueue:dispatch_get_main_queue()];
        [_xmpproster activate:self.xmppstream];
        
        [_xmpproster addDelegate:self delegateQueue:dispatch_get_main_queue()];
        
        [_xmpproster setAutoFetchRoster:YES];
        [_xmpproster setAutoAcceptKnownPresenceSubscriptionRequests:NO];
    }
}

-(void)loginWithName:(NSString *)userName andPassword:(NSString *)password sucessLogin:(sucessBlock)sucess
{
    _myJID = [XMPPJID jidWithUser:userName domain:DOMAINT resource:@"iOS"];
    self.sucesss = sucess;
    [self.xmppstream setMyJID:_myJID];
    if(![self.xmppstream isConnected])
    {
        [self connect];
    }
}


-(void)connect
{
    NSError  *connectError = nil;
    if (![_xmppstream connectWithTimeout:XMPPStreamTimeoutNone error:&connectError]) {
        
        NSLog(@"XMPP Connect With Error : %@", connectError);
    }
}
-(void)authentication
{
    NSError *error = nil;
    if( ![self.xmppstream authenticateWithPassword:@"123456" error:&error])
    {
        NSLog(@"%@",error);
    }else
    {
        NSLog(@"sucess connect server");
    }
}

- (void)goOnline {
    XMPPPresence *presence = [XMPPPresence presence];
    [[self xmppstream] sendElement:presence];
}

-(void)offLine
{
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
    [[self xmppstream] sendElement:presence];
}

- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message {
    
    NSString *messageBody = [[message elementForName:@"body"] stringValue];
    NSLog(@"%@",messageBody);
}
- (void)xmppStreamWillConnect:(XMPPStream *)sender
{
    
    
}
//连接服务器成功
-(void)xmppStreamDidConnect:(XMPPStream *)sender
{
    [self authentication];
}
//登录成功
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    NSLog(@"sucess login");
    [self goOnline];
    if(self.sucesss)
    {
        self.sucesss();
    }
}
//登录失败
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    NSLog(@"%s登录失败",__func__);
}
//同步数据结束
- (void)xmppRosterDidEndPopulating:(XMPPRoster *)sender
{
    
}
//当好友有变化时候
- (void)xmppRosterDidChange:(XMPPRosterMemoryStorage *)sender
{
    [[NSNotificationCenter defaultCenter]postNotificationName:REFRESHFRIEND object:nil];
}

- (void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence
{
    
    NSString *message = [NSString stringWithFormat:@"【%@】想加你为好友",presence.from.bare];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:self cancelButtonTitle:@"拒绝" otherButtonTitles:@"同意", nil];
    [alertView show];
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {

        //请求的用户
        NSString *presenceFromUser =[NSString stringWithFormat:@"%@", [[_presence from] user]];
        
        XMPPJID *jid = [XMPPJID jidWithString:presenceFromUser];
        //接收添加好友请求
        [_xmpproster acceptPresenceSubscriptionRequestFrom:jid andAddToRoster:YES];
    }
}

@end
